let MAX = 4;
function save2Id(file, target) {
	var preview = document.getElementById(target);
	var max = preview.getAttribute("data-size");
	if (!max) {
		max = MAX;
	}
	var mazSize = max * 1024 * 1024;
	if (mazSize < file.size) {
		toast.warning("图片大小不能超过"+max+"MB");
		return;
	}
	
	var reader = new FileReader();
	reader.addEventListener("load", function() {
		var base64gif = reader.result; // your gif in base64 here
		preview.src = base64gif;
	}, false);
	if (file) {
		reader.readAsDataURL(file);
	}
}

function uploadThis(target, successFunc, failureFunc) {
	let aesKey = localStorage["aesKey"];
    let aesIv = localStorage["aesIv"];
    if (aesKey) {
        aesKey = CryptoJS.enc.Hex.parse(aesKey.toHex());
    }
    if (aesIv) {
        aesIv = CryptoJS.enc.Hex.parse(aesIv.toHex());
    }
	
	var url = target.getAttribute("data-url");
	var formData = new FormData();
	var file = target.files[0];
    formData.append("size", file.size);   
    formData.append("file", file);    //生成一对表单属性
    eachAttr(target, attr=>{
    	if (attr.name.substring(0, 9) == "data-par-") {
			var oname = attr.name.substring(9);
			var ovalue = attr.value;
			formData.append(oname, ovalue);
		}
    });
	
    if (aesKey) {
        let secretToken = new Object();
        secretToken.createTime = new Date();
        secretToken.uuid = uuid();
        if (url.indexOf("%") == -1) {
            secretToken.uri = encodeURI(url);
        } else {
            secretToken.uri = url;
        }
        secretToken.method = "POST";
        let src = JSON.stringify(secretToken);
        let config = {
                padding: CryptoJS.pad.Pkcs7
        };
        if (aesIv) {
            config.mode = CryptoJS.mode.CBC;
            config.iv = aesIv;
        } else {
            config.mode = CryptoJS.mode.ECB;
        }
        let enc = CryptoJS.AES.encrypt(src, aesKey, config);
        let enced = CryptoJS.enc.Base64.stringify(enc.ciphertext);
        document.cookie="secretToken="+enced+"; Max-Age=60; path=/";
    }
    
    $.ajax({
        type: "POST",      //因为是传输文件，所以必须是post
        url: url,         //对应的后台处理类的地址
        data: formData,
        dataType: "text",
        processData: false,
        contentType: false,
        success: function(data, textStatus, jqXHR) {
        	if (successFunc) {
				successFunc(jqXHR, jqXHR.responseText)
			} else {
                let message = getMessageJ(jqXHR);
				toast.success(message, ()=>reload());
			}
        },
        error: function(jqXHR) {
        	if (failureFunc) {
				failureFunc(jqXHR, jqXHR.responseText);
			} else {
                let message = getMessageJ(jqXHR);
				toast.failure(message);
			}
		},
		xhr: function () {
            var xhr = $.ajaxSettings.xhr();
            if (xhr.upload) {
            	var progress = target.getAttribute("data-progress");
            	var $progress = $(progress);
            	$progress.addClass("active");
            	
            	var start = new Date().getTime();
                //处理进度条的事件
                xhr.upload.addEventListener("progress", function(e) {
                	var percent = e.loaded / e.total * 100;
                	$progress.css("width", percent.toFixed(0) + "%");
                    $progress.text(percent.toFixed(2) + "%");
				}, false);
                
                //加载完成的事件
                xhr.addEventListener("load", function() {
                	//toast.success("上传文件完成");
                    setTimeout(()=>endProgress($progress), 2000);
				}, false);
                
                //加载出错的事件
                xhr.addEventListener("error", function(e) {
                	if (failureFunc == undefined) {
                		toast.failure("上传文件出错, 服务不可用或文件过大");
                        setTimeout(()=>endProgress($progress), 2000);
        			} else {
        				failureFunc(jqXHR, jqXHR.responseText);
        			}
				}, false);
                
                //加载取消的事件
                xhr.addEventListener("abort", function() {
                	toast.warning("上传文件取消");
                    setTimeout(()=>endProgress($progress), 2000);
				}, false);
                
                return xhr;
            }
        }
    });
}

function getMessageJ(jqXHR) {
    return decodeURIComponent(jqXHR.getResponseHeader('x-api-message'));
}

function endProgress($progress) {
	$progress.removeClass("active");
	$progress.text("0%");
	$progress.css("width", "0%");
}